import 'package:flutter/material.dart';
import '../model/health_record.dart';
import '../service/database_service.dart';
import 'date_time_picker.dart';

class AddActivityRecordDialog extends StatefulWidget {
  final String babyId;
  const AddActivityRecordDialog({Key? key, required this.babyId})
    : super(key: key);

  @override
  State<AddActivityRecordDialog> createState() =>
      _AddActivityRecordDialogState();
}

class _AddActivityRecordDialogState extends State<AddActivityRecordDialog> {
  final _formKey = GlobalKey<FormState>();
  DateTime _date = DateTime.now();
  final _activityController = TextEditingController();
  final _durationController = TextEditingController();
  final _noteController = TextEditingController();
  String _type = '户外活动';

  final List<String> _activityTypes = ['户外活动', '室内游戏', '运动', '早教', '游泳', '其他'];

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: const Text('添加活动记录'),
      content: Form(
        key: _formKey,
        child: SingleChildScrollView(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              DateTimeFormField(
                label: '活动时间',
                value: _date,
                onChanged: (value) => setState(() => _date = value),
                validator: (value) => value == null ? '请选择时间' : null,
              ),
              DropdownButtonFormField<String>(
                value: _type,
                decoration: const InputDecoration(labelText: '活动类型'),
                items:
                    _activityTypes
                        .map(
                          (type) =>
                              DropdownMenuItem(value: type, child: Text(type)),
                        )
                        .toList(),
                onChanged: (value) {
                  if (value != null) setState(() => _type = value);
                },
              ),
              TextFormField(
                controller: _activityController,
                decoration: const InputDecoration(labelText: '活动内容'),
                validator: (value) => value?.isEmpty ?? true ? '请输入活动内容' : null,
              ),
              TextFormField(
                controller: _durationController,
                decoration: const InputDecoration(labelText: '持续时间(分钟)'),
                keyboardType: TextInputType.number,
                validator: (value) {
                  if (value?.isEmpty ?? true) return '请输入持续时间';
                  if (int.tryParse(value!) == null) return '请输入有效的数字';
                  return null;
                },
              ),
              TextFormField(
                controller: _noteController,
                decoration: const InputDecoration(labelText: '备注'),
                maxLines: 2,
              ),
            ],
          ),
        ),
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.pop(context),
          child: const Text('取消'),
        ),
        TextButton(onPressed: _submit, child: const Text('保存')),
      ],
    );
  }

  void _submit() async {
    if (!_formKey.currentState!.validate()) return;

    try {
      await DatabaseService().addHealthRecord(
        HealthRecord(
          babyId: widget.babyId,
          type: RecordType.activity,
          timestamp: _date,
          data: {
            'type': _type,
            'activity': _activityController.text,
            'duration': int.parse(_durationController.text),
            'note': _noteController.text,
          },
        ),
      );
      if (mounted) Navigator.pop(context);
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text('保存失败: $e')));
      }
    }
  }

  @override
  void dispose() {
    _activityController.dispose();
    _durationController.dispose();
    _noteController.dispose();
    super.dispose();
  }
}
